package com.geekerp.authorization_server.config;

import com.geekerp.authorization_server.pojo.Oauth2BasicUser;
import com.geekerp.authorization_server.utils.RSAKeyUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final String PUBLIC_KEY_PATH = "D:\\project\\rsa.pub";
    private static final String PRIVATE_KEY_PATH = "D:\\project\\rsa.pri";
    private PublicKey publicKey;
    private PrivateKey privateKey;

    public JwtAuthenticationFilter() {
        try {
            this.publicKey = RSAKeyUtils.getPublicKey(PUBLIC_KEY_PATH);
            this.privateKey = RSAKeyUtils.getPrivateKey(PRIVATE_KEY_PATH);
        } catch (Exception e) {
            throw new RuntimeException("Failed to load RSA keys", e);
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    System.out.println("request token = " + token);
                }
            }
        }

        if (token != null) {
            try {
                Claims claims = Jwts.parserBuilder()
                        .setSigningKey(publicKey)
                        .build()
                        .parseClaimsJws(token)
                        .getBody();

                if (claims.getExpiration().after(new Date())) {
                    Oauth2BasicUser basicUser = new Oauth2BasicUser();
                    basicUser.setId(1);
                    basicUser.setName("云逸");
                    basicUser.setAccount("admin");
                    basicUser.setPassword("$2a$10$K7nVcC.75YZSZU1Fq6G6buYujG.dolGYGPboh7eQbtkdFmB0EfN5K");
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(basicUser, null, basicUser.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (Exception e) {
                log.error("JWT 解析失败", e);
            }
        }
        filterChain.doFilter(request, response);
    }
}